package com.yurendao.shop.forum.web;

import com.alibaba.fastjson.JSONObject;
import com.yurendao.shop.forum.domain.Comment;
import com.yurendao.shop.forum.domain.Ncategory;
import com.yurendao.shop.forum.domain.Note;
import com.yurendao.shop.forum.domain.NoteCate;
import com.yurendao.shop.forum.exception.CommentException;
import com.yurendao.shop.forum.exception.NoteException;
import com.yurendao.shop.forum.service.ForumService;
import com.yurendao.shop.forum.service.NoteCateService;
import com.yurendao.shop.forum.web.json.NoteJson;
import com.yurendao.shop.pager.domain.Page;
import com.yurendao.shop.utils.CommonUtils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by kong on 16/2/18.
 */
@Controller
@RequestMapping("/note")
public class NoteController {

    @Autowired
    private NoteCateService noteCateService;
    @Autowired
    private ForumService forumService;

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public JSONObject add(Note note){
        JSONObject jsonObject = new JSONObject();
        try {
            note.setId(CommonUtils.uuid());
            note.setNotedate(new Date());
            forumService.insertNote(note);
            jsonObject.put("data",note);
        }catch (NoteException e){
            jsonObject.put("error_code",e.getMessage());
        }
        return jsonObject;
    }

    @RequestMapping(value = "/pic",method = RequestMethod.POST)
    public JSONObject addNotePic(@RequestParam("pic") MultipartFile file,HttpServletRequest request){
        System.out.println("multipart");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 得到上传的文件
        MultipartFile mFile = file;
        // 得到上传服务器的路径
        String path = request.getSession().getServletContext()
                .getRealPath("/WEB-INF/uploadnote/");
        // 上传的文件的文件名编号防止文件重名
        String randomname = CommonUtils.uuid().concat(CommonUtils.uuid());
        InputStream inputStream = null;
        // 文件流写到服务器端
        FileOutputStream outputStream = null;
        try {
            inputStream = mFile.getInputStream();
            byte[] b = new byte[1048576];
            int length = inputStream.read(b);
            path += "//" + randomname;
            outputStream = new FileOutputStream(path);
            outputStream.write(b, 0, length);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @RequestMapping(value = "{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public JSONObject delete(@PathVariable("id")String noteid){
        JSONObject jsonObject = new JSONObject();
        try {
            forumService.deleteNoteByNid(noteid);
            jsonObject.put("success",202);
        }catch (NoteException e){
            jsonObject.put("error_code",e.getMessage());
        }
        return jsonObject;
    }

    @RequestMapping(value = "{id}",method = RequestMethod.PUT)
    @ResponseBody
    public JSONObject edit(@PathVariable("id")String noteid,Note note){
        JSONObject jsonObject = new JSONObject();
        try {
            System.out.println(note.getContent());
            System.out.println("PUT");
            jsonObject.put("success",202);
        }catch (NoteException e){
            jsonObject.put("error_code",e.getMessage());
        }
        return jsonObject;
    }

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public JSONObject ksearch(String key,@RequestParam(required = false)String orderByClause,@RequestParam(required = false)Integer pageOffset){
        if(pageOffset==null)
            pageOffset=1;
        JSONObject jsonObject = new JSONObject();
        try {
            Page<Note> datas = forumService.selectNoteByKeyWord("%"+key+"%", orderByClause,pageOffset);
            jsonObject.put("keyword", key);
            jsonObject.put("pageoffset", datas.getPageOffset());
            jsonObject.put("pagesize", datas.getTotalRecords());
            jsonObject.put("data", datas.getRecords());
            return jsonObject;
        } catch (NoteException e) {
            jsonObject.put("error_code", e.getMessage());
            return jsonObject;
        }
    }

    @RequestMapping(value = "{id}/comment/",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject addComment(@PathVariable("id")String noteid,Comment comment){
        JSONObject jsonObject = new JSONObject();
        try {
            comment.setNoteid(noteid);
            forumService.insertComment(comment);
            jsonObject.put("data",comment);
            jsonObject.put("success",202);
        }catch (CommentException e){
            jsonObject.put("error_code", e.getMessage());
        }
        return jsonObject;
    }

    @RequestMapping(value = "/comment/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public JSONObject deleteComment(@PathVariable("id")String noteid,@PathVariable("cid")String commentid){
        JSONObject jsonObject = new JSONObject();
        try {
            forumService.deleteCommentByCid(commentid);
            jsonObject.put("success",202);
        }catch (CommentException e){
            jsonObject.put("error_code", e.getMessage());
        }
        return jsonObject;
    }

    @RequestMapping(value = "{id}/comment",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getComment(@PathVariable("id")String noteid,@RequestParam(required = false)String orderByClause,@RequestParam(required = false)Integer pageOffset){
        if(pageOffset==null)
            pageOffset=1;
        JSONObject jsonObject = new JSONObject();
        try {
            Page<Comment> datas = forumService.selectCommentByNote(noteid, orderByClause, pageOffset);
            jsonObject.put("pageoffset", datas.getPageOffset());
            jsonObject.put("pagesize", datas.getTotalRecords());
            jsonObject.put("data", datas.getRecords());
            return jsonObject;
        } catch (CommentException e) {
            jsonObject.put("error_code", e.getMessage());
            return jsonObject;
        }
    }

    @RequestMapping(value = "{id}",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getNoteByCate(@PathVariable("id")Integer ncid,@RequestParam(required = false)String orderByClause,@RequestParam(required = false)Integer pageOffset){
        JSONObject jsonObject = new JSONObject();
        if(pageOffset==null)
            pageOffset=1;
        try {
            Page<Note> datas = noteCateService.findNoteByCate(ncid, orderByClause, pageOffset);
            jsonObject.put("ncid", ncid);
            jsonObject.put("pageoffset", datas.getPageOffset());
            jsonObject.put("pagesize", datas.getTotalRecords());
            jsonObject.put("data", datas.getRecords());
            return jsonObject;
        } catch (NoteException e) {
            jsonObject.put("error_code", e.getMessage());
            return jsonObject;
        }
    }

    @RequestMapping(value = "/cate",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getAllCate(){
        JSONObject jsonObject = new JSONObject();
        List<Ncategory> ncategories = noteCateService.getAllCategory();
        jsonObject.put("error_code",0);
        jsonObject.put("data",ncategories);
        return jsonObject;
    }

    @RequestMapping(value = "/ca",method = RequestMethod.GET)
    public ModelAndView model(String key,@RequestParam(required = false)String orderByClause,@RequestParam(required = false,defaultValue = "1")Integer pageOffset){
        ModelMap model = new ModelMap();
        try {
            Page<Note> datas = forumService.selectNoteByKeyWord("%"+key+"%", orderByClause,pageOffset);
            model.put("keyword", key);
            model.put("pageoffset", datas.getPageOffset());
            model.put("pagesize", datas.getTotalRecords());

            List<NoteJson> notejsons = new ArrayList<NoteJson>();
            for (int i = 0; i < datas.getRecords().size(); i++) {
                int commentCount = forumService.getCommentCountByNoteId(datas.getRecords().get(i).getId());
                NoteJson notejson = new NoteJson(datas.getRecords().get(i),commentCount);
                notejsons.add(notejson);
            }
            model.put("data", notejsons);
            return new ModelAndView("/luntan/luntan",model);
        } catch (NoteException e) {
            model.put("error_code", e.getMessage());
            return new ModelAndView("/404",model);
        }
    }

    @RequestMapping(value = "/cate",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject addCate(NoteCate noteCate){
        JSONObject jsonObject = new JSONObject();
        noteCateService.insertCate(noteCate.getNcname(),noteCate.getNpid());
        jsonObject.put("success",200);
        return jsonObject;
    }

    @RequestMapping(value = "/cate/{id}",method = RequestMethod.PUT)
    @ResponseBody
    public JSONObject editCate(@PathVariable("id")Integer ncid,NoteCate noteCate){
        JSONObject jsonObject = new JSONObject();
        noteCate.setNcid(ncid);
        noteCateService.updateCate(noteCate);
        jsonObject.put("success",200);
        return jsonObject;
    }

    @RequestMapping(value = "/cate/{id}",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject deleteCate(@PathVariable("id")Integer ncid){
        JSONObject jsonObject = new JSONObject();
        try {
            noteCateService.deleteNoteCate(ncid);
            jsonObject.put("success",200);
        }catch (Exception e){
            jsonObject.put("error_code",e.getMessage());
        }
        return jsonObject;
    }
}
